﻿(function (mx) {
    var _loadModsFn = mx.Config.loadModsFn;
    mx.Config.loadModsFn = function (rs, config) {
        if (rs.mods.length == 1 && rs.mods[0].factory) {
            var mod = rs.mods[0];
            config._success = config.success;
            config.success = function () {
                mod.status++;
                config._success();
            };
        }
        _loadModsFn(rs, config)
    };

    mx.add("jquery/jquery", [], function (require, exports, module) {
        return jQuery || (function () {
            var Node = require('node');
            return Node.all; // or module.exports=c;
        });
    });

    mx.add("jquery/validate/date", ["jquery/validate"], function (require, exports, module) {
        var validator = require("jquery/validate");
        validator.methods.date = function (value, element) {
            var result = /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/.test(value) || /^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/.test(value);

            return this.optional(element) || result;
        };
        return validator.methods.date;
    });
    mx.add("jquery/easyui/tabs", ["jquery/easyui", "styles/easyui/easyui.css"], function (require, exports, module) {
        var easyui = require("jquery/easyui");
        $(".tabs").addClass("easyui-tabs").tabs();
    });

    mx.add("jquery/easyui/tree", ["jquery/easyui", "styles/easyui/easyui.css"], function (require, exports, module) {
        var easyui = require("jquery/easyui");
        $(".tree").addClass("easyui-tree");
        var selectedNode = "";
        $(".tree").find("li").each(function () {
            if ($(this).attr("data-selected") == "True") {
                if (selectedNode != '') selectedNode += ',';
                selectedNode += $(this).attr("id");
            }
        });
        $(".tree").tree();
        var selecteds = selectedNode.split(",")
        if (selecteds != "") {
            for (var i = 0; i < selecteds.length; i++) {
                var node = $('.tree').tree('find', selecteds[i]);
                if (node) {
                    $('.tree').tree('select', node.target);
                }
            }
        }
        return easyui.tree;
    });
    mx.add("jquery/easyui/combotree", ["jquery/easyui", "styles/easyui/easyui.css"], function (require, exports, module) {
        var easyui = require("jquery/easyui");
        var combox = $('.combotree');
        //todo 考虑同时出现多个
        //  var val = $("input[name=" + combox.attr("id") + "]");

        var tree = $(".tree");
        var opts = $.extend({}, $.fn.combotree.defaults, $.fn.combotree.parseOptions(combox[0]), {
            data: $(".tree").data("tree").data,
            onSelect: function (node) {
                // val.val(node.id);
                //combox.val(node.text);
                var fun = combox.data("onSelect");
                if (fun) {
                    fun.call(combox, node);
                }
            }
        });
        combox.combo(opts);





        var panelCombox = combox.combo("panel");
        tree = tree.appendTo(panelCombox);
        combox.data("combotree", { options: opts, tree: tree });
        combox.combotree();

        return easyui.combotree;
    });
    mx.config({
        packages: {
            styles: {
                base: "/Styles"
            },
            js: {
                base: "/Scripts"
            }
        },
        modules: {
            "jquery/validate": {
                uri: "//cdn.bootcss.com/jquery-validate/1.15.0/jquery.validate.js",
                factory: function (require) {
                    var jq = require("jquery/jquery");
                    return jq.validator;
                },
                requires: ["jquery/jquery"]
            },
            "jquery/validate/unobtrusive": {
                uri: "//cdn.bootcss.com/jquery-validation-unobtrusive/3.2.5/jquery.validate.unobtrusive.min.js",
                factory: function (require) {
                    var jqVal = require("jquery/validate");
                    require("jquery/validate/date");
                    return jqVal.unobtrusive;
                },
                requires: ["jquery/validate", "jquery/validate/date"]
            },
            "highcharts/highcharts": {
                uri: "//cdn.bootcss.com/highcharts/4.2.5/highcharts.js",
                factory: function (require) {
                    return require("jquery/jquery");
                },
                requires: ["jquery/jquery"]
            },
            "highcharts/3d": {
                uri: "//cdn.bootcss.com/highcharts/4.2.5/highcharts-3d.js",
                factory: function (require) {
                    return require("highcharts/highcharts");
                },
                requires: ["highcharts/highcharts"]
            },
            "jquery/ui": {
                uri: "http://apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js",
                factory: function (require) {
                    var jq = require("jquery/jquery");
                    return jq.fn;
                },
                requires: ["jquery/jquery"]
            },
            "jquery/easyui": {
                uri: "http://www.jeasyui.net/Public/js/easyui/jquery.easyui.min.js",
                factory: function (require) {
                    var jq = require("jquery/jquery");
                    return jq.fn.plugin;
                },
                requires: ["jquery/jquery"]
            }
        }
    });
})(modulex);
var iui = (function (mx) {
    var Utils = mx.Loader.Utils;
    function ready(modIds, success, error) {
        mx.use("node", function (Node) {
            $(document).ready(function () {
                mx.use(modIds, success, error);
            });
        });
    }
    function useElements(elements, modIds, success, error) {
        mx.use(modIds, function () {
            if (success) {
                var args = [];
                args[0] = elements;
                for (var i = 0; i < arguments.length; i++) {
                    args[i + 1] = arguments[i];
                }
                success.apply(mx, args);
            }
        }, error);
    }
    return {
        ready: ready,
        run: function (test, modIds, success, error) {
            //为了解决JS在head处时，没有任何DOM加载完成，统一在documnet.loaded之后执行。
            ready("node", function (Node) {
                var doms, ret;
                if (typeof test == "string") {
                    ret = Node.all(test);
                } else {
                    ret = test(Node.all);
                }
                if (typeof ret == "object") {
                    doms = ret;
                    ret = doms.length > 0;
                }
                if (ret) {
                    var mods = Utils.createModules(modIds);
                    var unloadedMods = [];
                    Utils.each(mods, function (mod) {
                        unloadedMods.push.apply(unloadedMods, mod.requires);
                    });
                    if (unloadedMods.length == 0) {
                        useElements(doms, modIds, success, error);
                    }
                    else {
                        //为了解决因JS加载顺序和时间长短不同引发的错误。
                        mx.use(unloadedMods, function () {
                            useElements(doms, modIds, success, error);
                        });
                    }



                }

            });
        }
    };
})(modulex);

iui.run(function (node) {
    return node("[data-confirm]");
}, [], function (elements, Node) {
    elements.each(function (el) {
        el.on("click", function () {
            return confirm(el.attr("data-confirm"));
        })
    });
});


iui.run(function (node) {
    return node("form").all("[data-val=true]").length > 0;
}, ["jquery/validate/unobtrusive"]);

iui.run("input[type=datetime],input[type=date]", ["jquery/ui"],
    function (elements, Node, DatePicker) {
        elements.each(function (input) {
            $(input[0]).datepicker({ showMonthAfterYear: true, changeMonth: true, changeYear: true, dateFormat: 'yy-m-d' });
        });
    });

iui.run(".chart", ["highcharts/3d"],
    function (elements, chart) {
        elements.each(function (div) {
            var container = $(div[0]);
            //var chartConfig = $.parseJSON(container.html());
            var chartConfig = eval("(" + container.html() + ")");
            //debugger;
            // eval("(" +chartConfig.series[0].events.click+ ")")
            container.highcharts(chartConfig);
            container.show();
        });
    });

iui.run(".tabs", ["jquery/easyui/tabs"]);

iui.run(".tree", ["jquery/easyui/tree"]);

iui.run(".combotree", ["jquery/easyui/combotree"]);


iui.run("[data-sync]", [], function (elements, Node) {
    elements.each(function (el) {
        el.on("submit", function (e) {
            e.preventDefault();
            var action = "";
            if (typeof (el.attr('action')) != "undefined") {
                action = el.attr('action');
            } else {
                return;
            }
            var method = typeof (el.attr('method')) == "undefined" ? "post" : el.attr('method');
            var queryParam = $(el).serializeArray();
            var dataContainer = $("#" + el.attr('data-sync'));
            $.ajax({
                url: action,
                type: method,
                data: queryParam,
                dataType: "html",
                beforeSend: function (xh) {
                    el.find("[type='submit']").prop('disabled', true);
                    var layer = $("<div class='loading' style='position:absolute;'></div>");
                    layer.width(dataContainer.width());
                    layer.height(dataContainer.height());
                    layer.css({
                        //"left": dataContainer.offset().left + "px",
                        //"top": dataContainer.offset().top + "px"
                    });
                    dataContainer.empty();
                    dataContainer.append(layer);
                },
                success: function (htmldata) {
                    dataContainer.empty();
                    dataContainer.html(htmldata);
                    el.find("[type='submit']").prop('disabled', false);
                },
            })
        })
    });
});


iui.run(function (node) {
    return node("[class='pagination1']  a");
}, [], function (elements, Node) {
    elements.each(function (el) {
        el.on("click", function (e) {
            e.preventDefault();
            var pageNum = parseInt($(el).text());
            var form4search = $(el).parent().parent().parent().prev().prev().find("form")[0];
            var action = "";
            if (typeof ($(form4search).attr('action')) != "undefined") {
                action = $(form4search).attr('action');
            } else {
                return;
            }

            var queryParam = $(form4search).serializeArray();
            var dataContainer = $("#" + $(form4search).attr('data-sync'));
            $.ajax({
                url: action + "?page=" + pageNum,
                type: "get",
                data: queryParam,
                dataType: "html",
                beforeSend: function (xh) {
                    var layer = $("<div style='position:absolute;text-align:center;font-size:36px;color:red'>数据加载中...</div>");
                    layer.width(dataContainer.width());
                    layer.height(dataContainer.height());
                    layer.css({
                        "left": dataContainer.offset().left + "px",
                        "top": dataContainer.offset().top + "px"
                    });
                    dataContainer.empty();
                    dataContainer.append(layer);
                },
                success: function (htmldata) {
                    dataContainer.empty();
                    dataContainer.html(htmldata);
                },
            })
        })
    });
});


iui.run(function (node) {
    return node("[data-dialog]");
}, ["jquery/dialog"], function (elements, Node) {
    elements.each(function (el) {
        el.on("click", function (e) {
            e.preventDefault();
            var btnDialog = $(el);
            var values = new Array();
            values = btnDialog.attr("data-dialog").split(',');
            var url = values[0];
            var iframeheight = parseInt(values[1]);
            var iframewidth = parseInt(values[2]);
            var dialogTitle = values[3];
            var expression = values[4];
            var dialog, form;
            var html = "<div  style='width:" + iframewidth + "px;height:" + iframeheight + "px;'>" +
                   "<div class='row'><div class='col-xs-2' style='text-align:left' >" + dialogTitle + "</div><div class='col-xs-offset-8 col-xs-2' style='text-align:right'><a id='_dialog_close' style='margin-right:8px;'>关闭</a></div></div>" +
                  "<iframe frameBorder='0' scrolling='no' width='98%' height='90%'  title=\"" + dialogTitle + "\"   src=" + url + ">" +
                   "</iframe></div>";
            var htmlContents = $(html);
            htmlContents.find('#_dialog_close').on('click', function () {
                $.unblockUI();

            });
            $.blockUI({ message: htmlContents, css: { width: iframewidth, height: iframeheight, top: "20%", left: "30%" } });
            iui.dialog = {
                done: function (result) {
                    eval(expression + "('" + result + "')");
                    $.unblockUI();
                },
                close: function () {
                    $.unblockUI();
                }
            };
        });
    });
});


//iui.run(function (node) {
//    return node("[type='submit']");
//}, [], function (elements, Node) {
//    elements.each(function (el) {
//        el.on("click", function (e) {
//            $(el).prop('disabled', true);
//        });
//    });
//});

//iui.run(function (node) {
//    return node("body");
//}, ["jquery/dialog"], function () {
//    alert(1);
//});


iui.run(function (node) {
    return node("[data-alert]");
}, [], function (elements, Node) {
    elements.each(function (el) {
        el.on("click", function () {
            var params = new Array();
            params = el.attr("data-alert").split(',');
            $.ajax({
                url: params[0] + "&radom=" + Math.random(),
                type: "get",
                dataType: "text",
                success: function (data) {
                    if (data.toLowerCase() == "false") {
                        alert(params[1]);
                    }
                },
            })
            return;
        })
    });
});


iui.run(function (node) {
    return node("select[data-url],input[data-url]");
}, [], function (elements, Node) {
    elements.each(function (el) {
        el = $(el[0]);
        el.change(function () {
            window.location.href = el.attr("data-url") + "?" + el.attr("name") + "=" + this.value;
        });
    });
});

iui.run(function (node) {
    return node("input[data-sync]");
}, [], function (elements, Node) {
    var datasync = elements.attr("data-sync");
    $("input[type!=hidden][data-sync=" + datasync + "]").change(function () {
        $("input[data-sync=" + datasync + "]").val($(this).val());
    });

});